'use client'

import React, { useRef, useEffect } from 'react'
import { Card, Typography, Slider, Button, Space } from 'antd'
import {
    ZoomInOutlined,
    ZoomOutOutlined,
    RotateLeftOutlined,
    RotateRightOutlined,
    SettingOutlined
} from '@ant-design/icons'
import { useImageStore } from '@/stores/imageStore'
import { useUIStore } from '@/stores/uiStore'

const { Text } = Typography

// 面板组件
interface PanelProps {
    title: string
    imageData: unknown
    onPositionChange?: (position: number[]) => void
}

const ViewerPanel: React.FC<PanelProps> = ({ title, imageData, onPositionChange }) => {
    const canvasRef = useRef<HTMLCanvasElement>(null)

    useEffect(() => {
        if (canvasRef.current && imageData) {
            const canvas = canvasRef.current
            const ctx = canvas.getContext('2d')
            if (ctx) {
                // 响应式画布尺寸
                const rect = canvas.getBoundingClientRect()
                const width = rect.width || 400
                const height = rect.height || 300

                // 设置画布实际尺寸
                canvas.width = width
                canvas.height = height

                // 占位显示：绘制简单的网格和文字
                ctx.fillStyle = '#f0f0f0'
                ctx.fillRect(0, 0, width, height)

                // 绘制网格线
                ctx.strokeStyle = '#ddd'
                ctx.lineWidth = 1
                const gridSize = Math.min(width, height) / 10
                for (let i = 0; i < width; i += gridSize) {
                    ctx.beginPath()
                    ctx.moveTo(i, 0)
                    ctx.lineTo(i, height)
                    ctx.stroke()
                }
                for (let i = 0; i < height; i += gridSize) {
                    ctx.beginPath()
                    ctx.moveTo(0, i)
                    ctx.lineTo(width, i)
                    ctx.stroke()
                }

                // 绘制标题 - 响应式字体大小
                ctx.fillStyle = '#333'
                const fontSize = Math.max(12, Math.min(width, height) / 20)
                ctx.font = `${fontSize}px Arial`
                ctx.textAlign = 'center'
                ctx.fillText(title, width / 2, height / 2 - fontSize / 2)
                ctx.font = `${fontSize * 0.75}px Arial`
                ctx.fillText('等待后端数据', width / 2, height / 2 + fontSize / 2)
            }
        }
    }, [imageData, title])

    const handleCanvasClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
        const rect = e.currentTarget.getBoundingClientRect()
        const x = e.clientX - rect.left
        const y = e.clientY - rect.top
        onPositionChange?.([x, y, 0])
    }

    return (
        <div className="viewer-panel h-full flex flex-col">
            <div className="panel-header bg-gray-100 px-3 py-2 text-sm font-medium border-b">
                {title}
            </div>
            <div className="panel-content flex-1 flex items-center justify-center bg-black">
                <canvas
                    ref={canvasRef}
                    className="border cursor-crosshair w-full h-full max-w-full max-h-full"
                    onClick={handleCanvasClick}
                />
            </div>
        </div>
    )
}

export const Viewer3D: React.FC = () => {
    const { currentImageData } = useImageStore()
    const { panelStates, updatePanelState } = useUIStore()

    const synchronizePanels = (sourcePanel: string, position: number[]) => {
        console.log(`Synchronizing panels from ${sourcePanel}:`, position)
        // 这里将来会实现真正的面板同步逻辑
    }

    const handleZoomChange = (value: number) => {
        updatePanelState('axial', { zoom: value })
    }

    const handleWindowLevelChange = (value: number[]) => {
        updatePanelState('axial', { windowLevel: [value[0], value[1]] })
    }

    return (
        <div className="viewer-3d h-full flex flex-col slide-in-left">
            {/* 3D查看器响应式布局 */}
            <div className="viewer-grid flex-1 flex flex-col lg:grid lg:grid-cols-2 lg:grid-rows-2 gap-2 p-2">
                {/* 移动端：垂直堆叠布局 */}
                <div className="lg:hidden flex flex-col space-y-2 h-full">
                    {/* 主要切面显示 */}
                    <Card className="viewer-panel flex-1" bodyStyle={{ padding: 0, height: '100%' }}>
                        <ViewerPanel
                            title="轴位 (Axial)"
                            imageData={currentImageData}
                            onPositionChange={(pos) => synchronizePanels('axial', pos)}
                        />
                    </Card>

                    {/* 控制面板 - 移动端简化版 */}
                    <Card
                        title="控制"
                        className="viewer-panel"
                        bodyStyle={{ padding: '12px' }}
                        style={{ height: '200px' }}
                    >
                        <div className="space-y-3">
                            {/* 缩放控制 - 简化版 */}
                            <div>
                                <div className="flex items-center justify-between mb-1">
                                    <Text strong className="text-sm">缩放</Text>
                                    <Text type="secondary" className="text-xs">
                                        {(panelStates.axial.zoom * 100).toFixed(0)}%
                                    </Text>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Button
                                        type="text"
                                        icon={<ZoomOutOutlined />}
                                        size="small"
                                        onClick={() => handleZoomChange(Math.max(0.1, panelStates.axial.zoom - 0.1))}
                                    />
                                    <Slider
                                        min={0.1}
                                        max={5}
                                        step={0.1}
                                        value={panelStates.axial.zoom}
                                        onChange={handleZoomChange}
                                        className="flex-1"
                                    />
                                    <Button
                                        type="text"
                                        icon={<ZoomInOutlined />}
                                        size="small"
                                        onClick={() => handleZoomChange(Math.min(5, panelStates.axial.zoom + 0.1))}
                                    />
                                </div>
                            </div>

                            {/* 快速操作按钮 */}
                            <div>
                                <Text strong className="block mb-2 text-sm">快速操作</Text>
                                <Space wrap>
                                    <Button type="text" icon={<RotateLeftOutlined />} size="small">左转</Button>
                                    <Button type="text" icon={<RotateRightOutlined />} size="small">右转</Button>
                                    <Button type="text" icon={<SettingOutlined />} size="small">设置</Button>
                                </Space>
                            </div>
                        </div>
                    </Card>
                </div>

                {/* 桌面端：网格布局 */}
                <div className="hidden lg:contents">
                    {/* 轴位面板 */}
                    <Card className="viewer-panel" bodyStyle={{ padding: 0, height: '100%' }}>
                        <ViewerPanel
                            title="轴位 (Axial)"
                            imageData={currentImageData}
                            onPositionChange={(pos) => synchronizePanels('axial', pos)}
                        />
                    </Card>

                    {/* 矢状面板 */}
                    <Card className="viewer-panel" bodyStyle={{ padding: 0, height: '100%' }}>
                        <ViewerPanel
                            title="矢状位 (Sagittal)"
                            imageData={currentImageData}
                            onPositionChange={(pos) => synchronizePanels('sagittal', pos)}
                        />
                    </Card>

                    {/* 冠状面板 */}
                    <Card className="viewer-panel" bodyStyle={{ padding: 0, height: '100%' }}>
                        <ViewerPanel
                            title="冠状位 (Coronal)"
                            imageData={currentImageData}
                            onPositionChange={(pos) => synchronizePanels('coronal', pos)}
                        />
                    </Card>

                    {/* 控制面板 - 桌面端完整版 */}
                    <Card
                        title="控制面板"
                        className="viewer-panel"
                        bodyStyle={{ padding: '16px' }}
                    >
                        <div className="space-y-4 h-full overflow-y-auto">
                            {/* 缩放控制 */}
                            <div>
                                <Text strong className="block mb-2">缩放</Text>
                                <div className="flex items-center space-x-2">
                                    <Button
                                        type="text"
                                        icon={<ZoomOutOutlined />}
                                        size="small"
                                        onClick={() => handleZoomChange(Math.max(0.1, panelStates.axial.zoom - 0.1))}
                                    />
                                    <Slider
                                        min={0.1}
                                        max={5}
                                        step={0.1}
                                        value={panelStates.axial.zoom}
                                        onChange={handleZoomChange}
                                        className="flex-1"
                                    />
                                    <Button
                                        type="text"
                                        icon={<ZoomInOutlined />}
                                        size="small"
                                        onClick={() => handleZoomChange(Math.min(5, panelStates.axial.zoom + 0.1))}
                                    />
                                </div>
                                <Text type="secondary" className="text-xs">
                                    {(panelStates.axial.zoom * 100).toFixed(0)}%
                                </Text>
                            </div>

                            {/* 窗宽窗位控制 */}
                            <div>
                                <Text strong className="block mb-2">窗宽窗位</Text>
                                <div className="space-y-2">
                                    <div>
                                        <Text className="text-xs text-gray-600">窗宽: {panelStates.axial.windowLevel[1]}</Text>
                                        <Slider
                                            min={1}
                                            max={4000}
                                            value={panelStates.axial.windowLevel[1]}
                                            onChange={(value) => handleWindowLevelChange([panelStates.axial.windowLevel[0], value])}
                                        />
                                    </div>
                                    <div>
                                        <Text className="text-xs text-gray-600">窗位: {panelStates.axial.windowLevel[0]}</Text>
                                        <Slider
                                            min={-1000}
                                            max={3000}
                                            value={panelStates.axial.windowLevel[0]}
                                            onChange={(value) => handleWindowLevelChange([value, panelStates.axial.windowLevel[1]])}
                                        />
                                    </div>
                                </div>
                            </div>

                            {/* 旋转控制 */}
                            <div>
                                <Text strong className="block mb-2">旋转</Text>
                                <Space>
                                    <Button
                                        type="text"
                                        icon={<RotateLeftOutlined />}
                                        size="small"
                                    >
                                        左转
                                    </Button>
                                    <Button
                                        type="text"
                                        icon={<RotateRightOutlined />}
                                        size="small"
                                    >
                                        右转
                                    </Button>
                                </Space>
                            </div>

                            {/* 测量工具 */}
                            <div>
                                <Text strong className="block mb-2">测量工具</Text>
                                <Space direction="vertical" size="small" className="w-full">
                                    <Button size="small" block>距离测量</Button>
                                    <Button size="small" block>角度测量</Button>
                                    <Button size="small" block>面积测量</Button>
                                </Space>
                            </div>

                            {/* 设置 */}
                            <div className="pt-2 border-t">
                                <Button
                                    type="text"
                                    icon={<SettingOutlined />}
                                    size="small"
                                    block
                                >
                                    高级设置
                                </Button>
                            </div>
                        </div>
                    </Card>
                </div>
            </div>
        </div>
    )
}

export default Viewer3D